package com.gmrz.uaf.servlet.v1.handler;

import com.gmrz.uaf.common.Constants;
import com.gmrz.uaf.common.GuiceUtil;
import com.gmrz.uaf.protocol.v1.json.UAFSchemaBuilder;
import com.gmrz.uaf.protocol.v1.schema.RegistrationRequest;
import com.gmrz.uaf.remote.protocol.v1.processor.UAPIDAuthInitProcessor;
import com.gmrz.uaf.server.ServerContext;
import com.gmrz.uaf.servlet.v1.request.IDAuthContext;
import com.gmrz.uaf.servlet.v1.request.ReceiveReqPayload;
import com.gmrz.uaf.servlet.v1.response.FidoRespPayload;
import com.gmrz.uaf.servlet.v1.validation.PayloadValidationException;
import com.gmrz.uaf.servlet.v1.validation.RestValidator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by gongyuqiang on 2017/5/8.
 */
public class UAPIDAuthRequestHandler extends UAFBaseHandler {
    private static final Logger LOG = LogManager.getLogger(UAPIDAuthRequestHandler.class);

    /**
     * {
     *     "context":{
     *          "transNo":"32characters",
     *          "appID","001",
     *          "authType":"12"
     *     }
     * }

     * @param request
     * @return
     *{
     *     "statusCode":1200,
     *     "description":"OK",
     *     "uafRequest":"[
     *     "[{\"header\":{....},\"policy\":{.....}}]"
     *     ]"
     * }
     */
    public String regInit(String request) {
        LOG.info("[/idauth/receive][begin]");
        ServerContext.getServerContext().getFidoLog().setRequest(request);
        Gson gson = UAFSchemaBuilder.getGson();
        FidoRespPayload<String> respPayload = new FidoRespPayload<String>();
        Type reqType = new TypeToken<ReceiveReqPayload<IDAuthContext>>() {}.getType();
        String response = null;
        try {
            // 将请求串转为对象
            ReceiveReqPayload<IDAuthContext> reqPayload = gson.fromJson(request, reqType);
            ServerContext.getServerContext().setBase64(reqPayload.getContext().isBase64());
            // 记录日志
            logRequest(request,reqPayload.getContext().getTransNo(),reqPayload.getContext().getUserName(),
                    reqPayload.getContext().getAppID(), reqPayload.getContext().getAuthType(),reqPayload.getContext().getTransType(), Constants.Method.IDAUTH_INIT);
            // 校验请求参数
            validate(reqPayload);
            UAPIDAuthInitProcessor processor = GuiceUtil.getProcessorInjector()
                    .getInstance(UAPIDAuthInitProcessor.class);
            IDAuthContext context = reqPayload.getContext();
            // 业务处理
            List<RegistrationRequest> requests = processor.request(context.getUserName(), context.getAppID(), context.getAuthType(),context.getTransType());
            LOG.info("response=" + gson.toJson(requests));
            response = buildReceiveResponse(gson, respPayload, requests);
        } catch (Exception ex) {
            LOG.error(ex);
            response = buildFidoRespFromException(respPayload, ex);
        }
        LOG.info("[/idauth/receive][end]");
        return response;
    }

    void validate(ReceiveReqPayload<IDAuthContext> reqPayload) throws PayloadValidationException
    {
        if ((null == reqPayload) || (null == reqPayload.getContext())) {
            throw new PayloadValidationException("context", RestValidator.VALIDATION_ERROR.EMPTY);
        }
        IDAuthContext context = reqPayload.getContext();
        RestValidator.validate("appID",context.getAppID());
        RestValidator.validate("authType",context.getAuthType());

        RestValidator.validate("transNo",context.getTransNo());

    }
}
